<template>
    <a-layout id="layout-register">
        <a-layout-header :style="headerStyle" class="phone_logo">
            <img :src="logo" class="logo" />
            {{name}}
        </a-layout-header>
        <a-layout-content :style="contentStyle">
            <a-row type="flex" justify="center" align="middle" style="height:100%;flex:1;">
                <!-- //轮播图 -->
                <a-col>
                    <a-carousel autoplay arrows class="my-carousel phone_style">
                        <div slot="prevArrow" class="custom-slick-arrow" style="left: 10px;z-index: 1">
                            <a-icon type="left-circle" />
                        </div>
                        <div slot="nextArrow" class="custom-slick-arrow" style="right: 10px">
                            <a-icon type="right-circle" />
                        </div>
                        <div v-for="(item,index) in loginImages" :key="index" style="height:500px;">
                            <img :src="item.imgUrl" />
                        </div>
                    </a-carousel>
                </a-col>
                <a-col>
                    <a-form-model ref="ruleForm" :model="ruleForm" :rules="rules" v-bind="layout" class="register-body ">
                        <div class="register-phone register-body-width" v-html="shareRemark"></div>
                        <div class="hr_sytle"></div>

                        <div class="register-body-width">

                            <a-form-model-item :wrapper-col="{ span: 24}" class="register-header class_tiles" style="width: 100%">用户注册</a-form-model-item>
                            <a-form-model-item has-feedback prop="userPhone">
                                <template slot="label"><span class="required-start">*</span>登录账户</template>
                                <a-input v-model.number="ruleForm.userPhone" placeholder="手机号码" class="phone_input" />
                            </a-form-model-item>
                            <a-form-model-item has-feedback v-show="isShowImgCode" prop="imgCode">
                                <template slot="label"><span class="required-start">*</span>图片验证码</template>
                                <a-input v-model="ruleForm.imgCode" autocomplete="off" style="width:120px;" class="phone_input" />
                                <div class="code" @click="referTimestamp">
                                    <img :src="verifyCodeUrl" @click="referTimestamp" />
                                </div>
                            </a-form-model-item>
                            <a-form-model-item has-feedback prop="vCode">
                                <template slot="label"><span class="required-start">*</span>验证码</template>
                                <a-input v-model.number="ruleForm.vCode" placeholder="请输入验证码" autocomplete="off" style="width:120px;" class="phone_input" />
                                <div class="code phone_code" @click="sendSms" :style="fontColor">{{codeCotent}}</div>
                            </a-form-model-item>
                            <a-form-model-item has-feedback prop="realName">
                                <template slot="label"><span class="required-start">*</span>姓　名</template>
                                <a-input v-model="ruleForm.realName" class="phone_input" />
                            </a-form-model-item>
                            <a-form-model-item has-feedback prop="email">
                                <template slot="label"><span class="required-start">*</span>邮　箱</template>
                                <a-input v-model="ruleForm.email" placeholder="584418600@qq.com" class="phone_input" />
                            </a-form-model-item>
                            <a-form-model-item has-feedback prop="password">
                                <template slot="label"><span class="required-start">*</span>登录密码</template>
                                <a-input v-model="ruleForm.password" type="password" autocomplete="off" class="phone_input" />
                            </a-form-model-item>
                            <a-form-model-item has-feedback prop="checkPassword">
                                <template slot="label"><span class="required-start">*</span>确认密码</template>
                                <a-input v-model="ruleForm.checkPassword" type="password" autocomplete="off" class="phone_input" />
                            </a-form-model-item>
                            <a-form-model-item has-feedback style="text-align: center;" class="required_phone">
                                <template slot="label"><span class="required-start">*</span>用户类型</template>
                                <a-radio-group style="margin-right: 80px;margin-top:7px;" v-model="ruleForm.userType" @change="changeType">
                                    <a-radio :value="1">单位</a-radio>
                                    <a-radio style="margin-left: 10px;" :value="2">个人</a-radio>
                                </a-radio-group>
                            </a-form-model-item>
                            <a-form-model-item has-feedback prop="companyName" v-if="isShowCompany">
                                <template slot="label"><span class="required-start">*</span>单位名称</template>
                                <a-input class="phone_input" v-model="ruleForm.companyName" v-show="isShowCompany" placeholder="单位负责人填写" :title="ruleForm.companyName" />
                            </a-form-model-item>
                            <a-form-model-item style="font-size:0.8rem;" class="agree-agreement" :wrapper-col="{ span: 24}">
                                <a-checkbox @change="onAgreeChange" :checked="isShowSubmitBtn" class="agreement-text">
                                    我已经阅读并同意
                                    <a @click="showModal('user')">《用户协议》</a>和
                                    <a @click="showModal('privacy')">《隐私政策》</a>
                                </a-checkbox>
                            </a-form-model-item>
                            <a-form-model-item :wrapper-col="{ span: 24}" class="reg-btn button_phone">
                                <!-- <a-button @click="resetForm('ruleForm')">重置</a-button> -->
                                <a-button type="primary" @click="submitForm('ruleForm')" :disabled="!isShowSubmitBtn" class="col-sm-8">注 册</a-button>
                            </a-form-model-item>
                            <a-form-model-item class="left_class">
                                <router-link to="login" class="text-center">已注册去登录</router-link>
                            </a-form-model-item>
                        </div>

                    </a-form-model>
                </a-col>
            </a-row>
            <a-modal title="" :visible="ModalVisible" @cancel="hideModal" width="1000px">
                <template slot="footer">
                    <a-button type="danger" @click="hideModal">关闭</a-button>
                </template>
                <div v-html="agreementMap.get(agreementKey)"></div>
            </a-modal>
        </a-layout-content>
        <a-layout-footer :style="footerStyle">
            {{copy}}
            <a href="http://beian.miit.gov.cn" target="_blank">{{ipc}}</a>
            客服电话：{{phone}}
        </a-layout-footer>
    </a-layout>
</template>
<script>
import logo from "@/assets/logo.png";
import { LoginConfig } from "@/api/login";
import { register, checkUser, sendUserCode } from "@/api/user";
import { getAgreement } from "@/api/agreement";

export default {
    metaInfo () {
        return {
            title: this.title,
            meta: this.meta
        };
    },
    computed: {
        verifyCodeUrl: function () {
            const { verifyCode, timestamp } = this;
            console.log(verifyCode + timestamp + "&userPhone=" + this.ruleForm.userPhone);

            return verifyCode + timestamp + "&userPhone=" + this.ruleForm.userPhone;
        }
    },
    data () {
        let checkPhone;
        let checkCode;
        let checkCompany;
        let checkUserEmail;
        let emailTest = /^\w[-\w.+]*@([A-Za-z0-9][-A-Za-z0-9]+\.)+[A-Za-z]{2,14}/;
        let numReg = /^[0-9]*$/;

        //手机号校验
        let checkUserPhone = (rule, value, callback) => {
            clearTimeout(checkPhone);
            if (!value) {
                return callback(new Error("请输入手机号"));
            }
            checkPhone = setTimeout(() => {
                if (!Number.isInteger(value)) {
                    callback(new Error("手机号格式不正确"));
                    this.isShowImgCode = false;
                } else {
                    if (String(value).length != 11) {
                        callback(new Error("手机号格式不正确"));
                        this.isShowImgCode = false;
                    } else {
                        callback();
                        checkUser({ userPhone: value }).then(response => {
                            console.log(response)
                            if (response.code === 200) {
                                this.isShowImgCode = true;
                            }
                        });
                    }
                }
            }, 100);
        };
        //图片验证码校验
        let checkImgCode = (rule, value, callback) => {
            if (!value) {
                callback(new Error("验证码不能为空"));
            } else if (value.length == 4) {
                callback();
            } else {
                callback(new Error("验证码不正确"));
            }
        };
        //短信验证码校验
        let checkVCode = (rule, value, callback) => {
            if (!value) {
                callback(new Error("验证码不能为空"));
            } else if (!Number.isInteger(value)) {
                callback(new Error("验证码格式不正确"));
            } else if (String(value).length != 6) {
                callback(new Error("验证码格式不正确"));
            } else {
                checkUser({ userPhone: this.ruleForm.userPhone, code: value }).then(
                    response => {
                        if (response.code == 200) {
                            callback();
                        } else {
                            callback(new Error(response.message));
                        }
                    }
                );
            }
        };
        //单位名称校验
        let checkCompanyName = (rule, value, callback) => {
            clearTimeout(checkCompany);
            if (!value) {
                callback(new Error("请输入单位名称"));
                return;
            }
            checkCompany = setTimeout(() => {
                checkUser({ companyName: value }).then(response => {
                    if (response.code == 200) {
                        callback();
                    } else {
                        callback(new Error(response.message));
                    }
                });
            }, 100);
        };
        //姓名校验
        let checkRealName = (rule, value, callback) => {
            if (!value) {
                callback(new Error("请输入姓名"));
            } else {
                callback();
            }
        };
        //邮箱校验
        let checkEmail = (rule, value, callback) => {
            clearTimeout(checkUserEmail);
            if (!value) {
                callback(new Error("请输入邮箱"));
            } else if (!emailTest.test(value)) {
                callback(new Error("邮箱格式不正确"));
            } else {
                checkUserEmail = setTimeout(() => {
                    checkUser({ email: value }).then(response => {
                        if (response.code == 200) {
                            callback();
                        } else {
                            callback(new Error(response.message));
                        }
                    });
                }, 100);
            }
        };
        //密码校验
        let validatePass = (rule, value, callback) => {
            if (value === "") {
                callback(new Error("请输入密码"));
            } else {
                if (value.length < 6 || value.length > 14) {
                    callback(new Error("密码长度为6~14个字符"));
                }
                if (new RegExp(numReg).test(value)) {
                    callback(new Error("密码不能是纯数字"));
                }
                if (this.ruleForm.checkPassword !== "") {
                    this.$refs.ruleForm.validateField("checkPassword");
                }
                callback();
            }
        };
        let validatePass2 = (rule, value, callback) => {
            if (value === "") {
                callback(new Error("请再次输入密码"));
            } else if (value !== this.ruleForm.password) {
                callback(new Error("密码不一致,请重新输入!"));
            } else {
                callback();
            }
        };
        return {
            headerStyle: {}, //头部样式
            contentStyle: {
                backgroundRepeat: "round"
            }, //中部样式
            footerStyle: {}, //底部样式
            logo, //logo
            name: "", //网址名称
            copy: "© 2019", //版权信息
            phone: "188200", //客服电话
            ipc: "渝IPCP备", //备案信息
            title: "",
            meta: [],
            status: 1, //网站状态(0:关闭 1:开启)
            cause: "系统维护...", //关闭原因
            ruleForm: {
                password: "",             //密码
                checkPassword: "",        //确定密码
                userPhone: "",            //手机号码（用户名）
                imgCode: "",
                vCode: "",                //短信验证码
                userType: 1,           //1：单位 2：个人
                companyName: "",          //单位名称
                realName: "",             //真实姓名
                email: "",                //邮箱
                sharePhone: "",           //分享人的手机号码（非必填）
                shareCode: "",            //分享人的邀请码（非必填）
                shareRemark: '',      // 获取分享描述

            },
            rules: {
                //注册校验
                password: [{ validator: validatePass, trigger: "change" }],
                checkPassword: [{ validator: validatePass2, trigger: "change" }],
                userPhone: [{ validator: checkUserPhone, trigger: "change" }],
                imgCode: [{ validator: checkImgCode, trigger: "change" }],
                vCode: [{ validator: checkVCode, trigger: "change" }],
                companyName: [{ validator: checkCompanyName, trigger: "change" }],
                realName: [{ validator: checkRealName, trigger: "change" }],
                email: [{ validator: checkEmail, trigger: "change" }]
            },
            layout: {
                labelCol: { span: 7 },
                wrapperCol: { span: 14 }
            },
            codeCotent: "获取验证码",
            fontColor: "",
            isShowCompany: true,
            form: this.$form.createForm(this, { name: "advanced_search" }),
            isShowSubmitBtn: true, //是否显示‘注册’按钮
            ModalVisible: false,
            verifyCode: this.$Global.ApiBaseUrl + "/verifyCode/registerImageCode?timestamp=", //图片验证码地址
            timestamp: new Date().getTime(),
            isShowImgCode: false,
            loginImages: [],                       //轮播图
            agreementMap: new Map(),
            agreementKey: "",
            uid: '',
        };
    },
    created () {
        this.LoginConfig();
        this.getAgreement("user");
        this.getAgreement("privacy");
    },
    methods: {
        showModal (agreementKey) {
            Object.assign(this, { agreementKey });
            this.ModalVisible = true;
        },
        hideModal () {
            this.ModalVisible = false;
        },
        // onOk() {
        //   (this.isShowSubmitBtn = true), (this.ModalVisible = false);
        // },
        onAgreeChange (e) {
            console.log("接受协议：", e.target.checked);
            this.isShowSubmitBtn = e.target.checked;
        },
        //获取协议
        getAgreement (code) {
            getAgreement({ code }).then(response => {
                if (response.code === 200) {
                    const { data } = response;
                    this.agreementMap.set(code, data);
                }
            }).catch(error => { });
        },
        //获取登录页 配置
        LoginConfig () {
            console.log(this.$route);
            const url = this.$route.fullPath;
            if (url.indexOf('&') > 0) {
                const kv = url.split("&");
                this.uid = kv[2].split('=')[1];
            }
            LoginConfig({ shareId: this.uid }).then(res => {
                const { headerStyle, contentStyle, footerStyle } = this;
                const { code, data, message } = res;
                if (code == 200) {
                    this.shareRemark = res.data.shareContent;
                    const { name, logo, copy, phone, ipc, title, backColor, backImgUrl, keyWord, description, status, cause, loginImages } = data;
                    Object.assign(contentStyle, {
                        backgroundColor: backColor,
                        backgroundImage: `url(${backImgUrl})`
                    });
                    Object.assign(headerStyle, {
                        backgroundColor: backColor
                    });
                    Object.assign(footerStyle, {
                        backgroundColor: backColor
                    });
                    let meta = new Array();
                    if (keyWord) {
                        meta.push({
                            // set meta
                            name: "keyWords",
                            content: keyWord
                        });
                    }
                    if (description) {
                        meta.push({
                            // set meta
                            name: "description",
                            content: description
                        });
                    }
                    Object.assign(this, {
                        title, name, logo, copy, phone, ipc, loginImages, meta
                    });
                    console.log("this.meta:", this.meta, this.loginImages);
                }
            });
        },
        submitForm (formName) {
            const { isShowSubmitBtn } = this;
            if (!isShowSubmitBtn) {
                this.$message.warn("请勾选'阅读并接受'用户协议");
            }
            this.ruleForm.sharePhone = this.getUrlKey("share", window.location.href);
            this.ruleForm.shareCode = this.getUrlKey("code", window.location.href);
            this.$refs[formName].validate(valid => {
                if (valid) {
                    if (!this.ruleForm.userType) {
                        this.$message.error("请选择用户类型");
                        return;
                    }
                    // this.ModalVisible = false;
                    register(this.ruleForm).then(response => {
                        if (response.code == 200) {
                            this.$message.success("注册成功");
                            this.$store.dispatch("Logout").then(() => {
                                this.$router.push({ path: "login" });
                            });
                            // this.ModalVisible = true;
                        }
                    });
                } else {
                    console.log("error submit!!");
                    return false;
                }
            });
        },
        //发送短信验证码
        sendSms () {
            this.$refs["ruleForm"].validateField("userPhone", valid => {
                if (!valid) {
                    this.$refs["ruleForm"].validateField("imgCode", valid => {
                        if (!valid) {
                            sendUserCode({
                                userPhone: this.ruleForm.userPhone,
                                imgCode: this.ruleForm.imgCode
                            }).then(response => {
                                if (response.code == 200) {
                                    this.$message.success("发送成功");

                                    let t = 60;
                                    this.fontColor = "color: #caced6; pointer-events: none;";
                                    let code = setInterval(() => {
                                        if (t == 0) {
                                            this.codeCotent = "获取验证码";
                                            this.fontColor = "";
                                            clearInterval(code);
                                            return false;
                                        }
                                        this.codeCotent = "获取验证码(" + t-- + ")";
                                    }, 1000);
                                } else {
                                    this.timestamp = new Date().getTime();
                                }
                            });
                        }
                    });
                }
            });
        },
        //重置表单
        resetForm (formName) {
            this.$refs[formName].resetFields();
        },
        //注册
        registe (e) {
            e.preventDefault();
            this.form.validateFields((err, values) => { });
        },
        changeType (value) {
            const type = this.ruleForm.userType;
            console.log("type", this.ruleForm.userType);
            if (type == 1) {
                this.isShowCompany = true;
            } else {
                this.isShowCompany = false;
            }
        },
        getUrlKey (name, url) {
            return (
                decodeURIComponent(
                    (new RegExp("[?|&]" + name + "=" + "([^&;]+?)(&|#|;|$)").exec(
                        url
                    ) || [, ""])[1].replace(/\+/g, "%20")
                ) || null
            );
        },
        //刷新时间
        referTimestamp () {
            this.timestamp = new Date().getTime();
        }
    }
};
</script>
<style lang="less">
    //  手机适配
    @media (max-width: 500px) {
        body {
            min-width: 0 !important;
        }
        #layout-register .register-body {
            padding: 20px 0 0 0 !important;
            width: 100vw !important;
        }
        .register-body-width {
            width: 97vw !important;
            padding: 0 1vw 0 5vw;
        }
        .hr_sytle {
            border: 1px solid #cacaca;
            margin-top: 10px;
        }
        .register-header {
            text-align: center;
            font-size: 1.5rem !important;
            padding: 5px 0 5px 0;
            .ant-form-item-control-wrapper {
                width: 100%;
            }
        }
        .left_class {
            padding: 0 !important;
        }
        .code {
            border: 1px solid #cacaca;
            border-radius: 20px;
            text-align: center;
            line-height: 40px;
            height: 40px !important;
            padding: 0 10px 0 10px;
            background: #1890ff;
            color: #fff;
        }

        .register-body {
            width: 430px;
            background: #ffffff;
            box-shadow: 0 0 0 #fff !important;
            padding: 30px 20px;
        }

        .required_phone {
            .ant-form-item-children {
                float: left;
            }
        }

        .ant-form-item-control-wrapper {
            width: 70%;
        }
        .phone_style {
            display: none;
        }
        .phone_logo {
            text-align: center;
        }
        .agree-agreement {
            .ant-form-item-control {
                width: 100%;
            }
            .ant-form-item-control-wrapper {
                width: 100%;
            }
        }
        .button_phone {
            .ant-form-item-control-wrapper {
                width: 100%;
            }
            button {
                height: 50px;
                font-size: 1.5rem;
            }
        }
        .phone_input {
            height: 42px;
        }
        .ant-form-item-label {
            // border: 1px solid red;
            padding: 0 5px 0 0;
            width: 28%;
            line-height: 3;
        }
        #layout-register .ant-form-item {
            display: flex;
        }
    }
    @media (min-width: 500px) {
        .register-phone {
            display: none;
        }
    }
    #layout-register {
        @media (min-width: 700px) {
            .my-carousel {
                width: 700px !important;
            }
        }
        @media (max-width: 700px) {
            .my-carousel {
                width: 100vw !important;
            }
            .ant-col-offset-4 {
                margin-left: 0px !important;
            }
        }
        .left_class {
            padding-left: 16.7%;
        }
        .my-carousel {
            .slick-list {
                height: 500px;
                img {
                    max-height: 100%;
                }
            }
        }
        height: 100%;
        width: 100%;
        .agree-agreement .ant-form-item-control {
            line-height: 20px;
            text-align: center;
            .agreement-text {
                font-weight: normal !important;
                color: gray;
            }
        }
        //头部样式
        .ant-layout-header {
            height: 70px;
            background: #fff;
            color: #333;
            font-size: 2rem;
            white-space: nowrap;
            text-overflow: ellipsis;
            overflow: hidden;
        }
        //中部样式
        .ant-layout-content {
            min-height: auto;
        }
        //底部
        .ant-layout-footer {
            background: #fff;
            text-align: center;
        }
        //轮播图样式
        .ant-carousel .slick-slide {
            text-align: center;
            // height: 160px;
            // line-height: 160px;
            // background: #364d79;
            overflow: hidden;
        }
        .ant-carousel .custom-slick-arrow {
            width: 25px;
            height: 25px;
            font-size: 25px;
            color: #0069d9;
            background-color: rgba(31, 45, 61, 0.11);
            opacity: 0.3;
        }
        .ant-carousel .custom-slick-arrow:before {
            display: none;
        }
        .ant-carousel .custom-slick-arrow:hover {
            opacity: 0.5;
        }

        .ant-carousel .slick-slide h3 {
            color: #fff;
        }

        .ant-carousel .slick-dots {
            height: auto;
        }
        .ant-carousel .slick-slide img {
            // border: 5px solid #fff;
            display: block;
            margin: auto;
            max-width: 80%;
        }
        .ant-carousel .slick-thumb {
            bottom: -45px;
        }
        .ant-carousel .slick-thumb li {
            width: 60px;
            height: 45px;
        }
        .ant-carousel .slick-thumb li img {
            width: 100%;
            height: 100%;
            filter: grayscale(100%);
        }
        .ant-carousel .slick-thumb li.slick-active img {
            filter: grayscale(0%);
        }

        //注册 主体
        .register-body {
            width: 430px;
            background: #ffffff;
            box-shadow: 0 0 1px rgba(0, 0, 0, 0.125), 0 1px 3px rgba(0, 0, 0, 0.2);
            padding: 30px 20px;
        }

        .logo {
            height: 100%;
        }
        .ant-form-item {
            margin-bottom: 10px !important;
        }
        .reg-btn .ant-form-item-children {
            display: flex;
            justify-content: center;
            line-height: 1px !important;
        }
        .register-header {
            text-align: center;
            font-size: 2.1rem;
        }
        .form-inline label {
            justify-content: left !important;
        }
        .form-inline > .col {
            margin-bottom: 1.5rem !important;
        }
        .icons-list /deep/ .anticon {
            margin-right: 8px;
            font-size: 16px;
        }
        .ant-advanced-search-form {
            padding: 24px;
            background: #fbfbfb;
        }

        .ant-advanced-search-form .ant-form-item {
            display: flex;
        }

        .ant-advanced-search-form .ant-form-item-control-wrapper {
            flex: 1;
        }

        #components-form-demo-advanced-search .ant-form {
            max-width: none;
        }
        #components-form-demo-advanced-search .search-result-list {
            margin-top: 16px;
            background-color: #fafafa;
            min-height: 200px;
            text-align: center;
            padding-top: 80px;
        }
        .code {
            float: right;
            width: auto;
            height: 32px;
            cursor: pointer;
            text-align: center;
        }
    }
</style>
